<template>
  <BasicModal v-bind="$attrs" @cancel="closeNode" @register="registerModal" destroyOnClose :title="title" width="75%" @ok="handleSubmit">
      <!-- <BasicForm @register="registerForm"/> -->
      <a-row>
        <a-col :md="4" :sm="4" style="border-right: 1px solid #999">
<!--          选择流程节点-->
          <a-steps direction="vertical" :current="current" size="small">
            <template  v-for="item,i in nodeList">
              <a-step style="cursor: pointer;" :title="item.title"
                      :description="item.description" :status="i==current?'process':'wait'"
                      @click="change_steps(item,i)"/>
            </template>
          </a-steps>
        </a-col>
        <a-col :md="20" :sm="20">
            <a-alert message="温馨提示：若流程运行至未分配审批人员的审批节点时，流程将自动中断取消！" banner />
            <span></span>
            <a-form ref="formRef" :model="spry" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-form-item label="节点名称" >
              <span class="nodespan">{{editNode.title}}</span>
            </a-form-item>
            <a-form-item  label="节点类型" >
              <span class="nodespan">{{dictNodeType[editNode.type]}}</span>
            </a-form-item>
            <a-alert type="info" message="每个节点设置，如有修改都请保存一次，跳转节点后数据不会自动保存！" banner />
            <br/>
            <a-form-item  label="审批人员" v-show="editNode.type==1">
              <a-checkbox-group @change="spryType" v-model:value="spryTypes" >
                  <!-- 0角色 1用户 2部门 3发起人 4发起人的部门负责人-->
                <a-checkbox value="0"> 根据角色选择 </a-checkbox>
                <a-checkbox value="1"> 直接选择人员 </a-checkbox>
                <a-checkbox value="2"> 部门 </a-checkbox>
                <a-checkbox value="5"> 部门负责人 </a-checkbox>
                <a-checkbox value="3">
                  发起人
                  <a-tooltip placement="topLeft" title="自动获取发起人">
                    <a-icon type="exclamation-circle" />
                  </a-tooltip>
                </a-checkbox>
                <a-checkbox value="4">
                  发起人的部门负责人
                  <a-tooltip placement="topLeft" title="自动获取发起人所在部门的负责人，即其上级领导。（如果其本身就是部门负责人，则指向发起人自己。）">
                    <a-icon type="exclamation-circle" />
                  </a-tooltip>
                </a-checkbox>
                <a-checkbox value="6">
                  表单变量
                  <a-tooltip placement="topLeft" title="填写与表单中相对应的变量，role:角色，user:人员：dept:部门：deptManage:部门负责人; 例如：variable:role,variable2:user;">
                    <a-icon type="exclamation-circle" />
                  </a-tooltip>
                </a-checkbox>
              </a-checkbox-group>
            </a-form-item>
             <!--0角色 1用户 2部门 3发起人 4发起人的部门负责人-->
             <a-form-item  label="选择角色" v-if="spryTypes.indexOf('0')>-1" >
              <!-- <JSelectRole rowKey="id" v-model:value="spry.roleId" :multi="true"></JSelectRole> -->
              <JDictSelectTag type="select" v-model:value="spry.roleIds" dictCode="sys_role,role_name,role_code" placeholder="请选择角色下拉"  ></JDictSelectTag>
            </a-form-item>
            <a-form-item  label="选择人员" v-if="spryTypes.indexOf('1')>-1"   >
              <!--  通过部门选择用户控件 -->
              <JSelectUser rowKey="username" v-model:value="spry.userIds" :multi="true"></JSelectUser>
            </a-form-item>
            <a-form-item  label="选择部门" v-if="spryTypes.indexOf('2')>-1" >
              <JSelectDept rowKey="id"  v-model:value="spry.departmentIds" :multi="true"></JSelectDept>
            </a-form-item>
            <a-form-item  label="选择部门负责人" v-if="spryTypes.indexOf('5')>-1"  >
              <JSelectDept  rowKey="id"  v-model:value="spry.departmentManageIds" :multi="true"></JSelectDept>
            </a-form-item>
            <a-form-item  label="输入表单变量" v-if="spryTypes.indexOf('6')>-1"  >
              <a-input v-model:value="spry.formVariables" :multi="true"></a-input>
            </a-form-item>
            </a-form>
        </a-col>
      </a-row>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,onMounted,watch,reactive} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm} from '/@/components/Form/index';
    import {formSchema} from '../processModelList.data';

    import { JSelectUser, JSelectDept, JDictSelectTag } from '/@/components/Form';

    import {editNodeUser,getProcessNode} from '../processModelList.api';
    import { useMessage } from "/@/hooks/web/useMessage";
 import { Form } from 'ant-design-vue';
        const { createMessage } = useMessage();
    // Emits声明
    const emit = defineEmits(['register','success']);
    //设置标题
    const title = "编辑流程节点";
    const isUpdate = ref(true);
    const  current= ref(0);
    const nodeList= ref([]);
    const dictOptions= ref([]);
    const  roleId=ref();
    const spryTypes= ref([]);
    // const nodeForm= ref({});
    const editNode=ref({});
    const formRef = ref();
    const updateRow=ref({});
    const useForm = Form.useForm;
    const spry=reactive({
          //选中的用户
          userIds:'',
          roleIds:'',
          departmentIds:'',
          departmentManageIds:'',
          formVariables:'',
          chooseSponsor:false,
          chooseDepHeader:false,
          formVariable:'',
          nodeId:'',
          procDefId:'',
        });
        const formData = ref({});
       const dictNodeType=ref({'0':'开始节点','1':'审批节点','2':'结束节点'});
    //表单配置
    // const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        // schemas: formSchema,
        // showActionButtonGroup: false,
        // baseColProps: {span: 24}
    // });
      //表单验证
      const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    //    // 重置表单
    //     await resetFields();
    //     setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
    //     isUpdate.value = !!data?.isUpdate;
    //     if (unref(isUpdate)) {
    //         //表单赋值
    //         await setFieldsValue({
    //             ...data.record,
    //         });
    //     }
    //     // 隐藏底部时禁用整个表单
      //  setProps({ disabled: false })
    //初始话代码
     getNodeData(data.record);
    });
//     onMounted(() => {
//   })
    //加载
    function getNodeData(row){
        console.log("row.id",row.id)
        updateRow.value = row;

        getProcessNode({ id:row.id}).then(res => {
            // 转换null为""
            nodeList.value = res||[];
            console.log("_this.nodeList",nodeList.value);
            if (nodeList.value.length>0){
              editNode.value = nodeList.value[current.value];
            }
        })
      };
    //关闭
    function closeNode(){
        console.log("关闭")
        current.value=0;
        spryTypes.value=[];
        emit('success');
    };
    //修改
   function change_steps(node,index){
        spryTypes.value = [];
        console.log('onChange:', node);
       current.value = index;
       editNode.value = node;
        /* 0角色 1用户 2部门 3发起人 4发起人的部门负责人 5部门的部门负责人*/
        spry.chooseDepHeader = node.chooseDepHeader||false;
        if (spry.chooseDepHeader) spryTypes.value.push('4') ;
        spry.chooseSponsor = node.chooseSponsor||false;
        if (spry.chooseSponsor) spryTypes.value.push('3') ;
        let userIds = [];
        for (const user of node.users||[]) {
          userIds.push(user.username);
        }
        spry.userIds = userIds.join(",");
        if (userIds.length>0) spryTypes.value.push('1') ;
        var roleIds = []
        for (const role of node.roles||[]) {
          roleIds.push(role.roleCode)
        }
        spry.roleIds = roleIds.join(",")
        if (roleIds.length>0) spryTypes.value.push('0') ;
        var departmentIds = []
        for (const department of node.departments||[]) {
          departmentIds.push(department.id)
        }
        spry.departmentIds = departmentIds.join(",")
        if (departmentIds.length>0) spryTypes.value.push('2') ;
        var departmentManageIds = []
        for (const departmentManage of node.departmentManages || []){
          departmentManageIds.push(departmentManage.id);
        }
        spry.departmentManageIds = departmentManageIds.join(",")
        if (departmentManageIds.length>0) spryTypes.value.push('5') ;
        console.log("回显this.spry",spry)
        console.log("回显this.spryTypes",spryTypes.value)
        spry.formVariables = node.formVariables||'';
        if (spry.formVariables) spryTypes.value.push('6');

      };
      //切换
      function spryType(types){
        console.log("this.spryTypes",spryTypes.value);
        /* 0角色 1用户 2部门 3发起人 4发起人的部门负责人 5部门负责人*/
        // this.spryTypes = types;
        if (spryTypes.value.indexOf('0')==-1) spry.roleIds = '';
        if (spryTypes.value.indexOf('1')==-1) spry.userIds = '';
        if (spryTypes.value.indexOf('2')==-1) spry.departmentIds = '';
        if (spryTypes.value.indexOf('5')==-1) spry.departmentManageIds = '';
        if (spryTypes.value.indexOf('6')==-1) spry.formVariable = '';
        //是否选中发起人
        spry.chooseSponsor = spryTypes.value.indexOf('3')>-1 ;
        //是否选中发起人的部门领导
        spry.chooseDepHeader = spryTypes.value.indexOf('4')>-1 ;

        console.log("this.spry",spry)
      };
      function sprySubmit() {
        // var _this = this;
        // if (this.spryTypes.length==0){
        //   _this.$message.error("必须选择审批人！");
        //   return;
        // }
        // _this.confirmLoading = true;
        // this.spry.nodeId = this.editNode.id;
        // this.spry.procDefId = this.editNode.procDefId;
        // this.postFormAction(_this.url.editNodeUser,this.spry).then(res => {
        //   if (res.success) {
        //     _this.$message.success("操作成功");
        //     /*保存成功后回显数据*/
        //     _this.getNodeData(_this.updateRow);
        //   }else {
        //     _this.$message.error(res.message);
        //   }
        // }).finally(() => _this.confirmLoading = false);
      };
    //表单提交事件
    async function handleSubmit(v) {
      try {
      if(editNode.value.type=='0'||editNode.value.type=='2'){
        createMessage.error("开始节点和结束节点不需要配置");
        return;
      }
      if (spryTypes.value.length==0){
          createMessage.error("必须选择审批人！");
          return;
      }
      setModalProps({confirmLoading: true});
      spry.nodeId = editNode.value.id;
      spry.procDefId = editNode.value.procDefId;
      console.log("spry",spry);
        //关闭弹窗
        // closeModal();
        //刷新列表
        // emit('success');

     await editNodeUser(spry);
        /*保存成功后回显数据*/
        getNodeData(updateRow.value);
    
      } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>